/*************************************************************************
	> File Name: tcp_server.hpp
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/10/03 14:32
 ************************************************************************/

#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cerrno>
#include "log.hpp"
#include <pthread.h>
#include "thread.hpp"
#include <unordered_map>
#include <sys/wait.h>

const int BUF_SIZE = 1024;

const void dictOnline(const int sock, const std::string &ip, const uint16_t port)
{
    char buffer[BUF_SIZE];
    static std::unordered_map<std::string, std::string> dict = {
        {"apple", "苹果"},
        {"banana", "香蕉"},
        {"orange", "橙子"},
        {"pen", "钢笔"}
    };
    ssize_t s = read(sock, buffer, sizeof buffer - 1);
    if (s > 0) {
        buffer[s] = 0;
        std::cout << "|" << ip << ":" << port << "|" << std::endl;
        std::string message;
        const auto it = dict.find(buffer);
        if (it == dict.end()) {
            message = "can not translate this word:";
            message += buffer;
        } else {
            message = it->second;
        }
        write(sock, message.c_str(), message.size());
    } else if (s == 0) {
        logMessage(NORMAL, "%s:%d, shutdown.", ip.c_str(), port);
    } else {
        logMessage(ERROR, "read socket error, %d:%s", errno, strerror(errno));
    }
    close(sock);
}

class TcpServer
{
public:
    TcpServer (uint16_t port, std::string ip = "0.0.0.0"):_port(port), _ip(ip), _listensock(-1)
    {}

    void initServer()
    {
        if ((_listensock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
            logMessage(FATAL, "socket error, %d:%s", errno, strerror(errno));
            exit(2);
        }
        logMessage(NORMAL, "create sock success");
        struct sockaddr_in local;
        memset(&local, 0, sizeof local);
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = inet_addr(_ip.c_str());
        if (bind(_listensock, (struct sockaddr*)&local, sizeof local) < 0) {
            logMessage(FATAL, "bind error, %d:%s", errno, strerror(errno));
            exit(3);
        }
        if (listen(_listensock, gbacklog) < 0) {
            logMessage(FATAL, "listen error, %d:%s", errno, strerror(errno));
            exit(4);
        }
        logMessage(NORMAL, "init tcp-server success");
    }

    void start()
    {
        while (1) {
            struct sockaddr_in src;
            socklen_t len = sizeof src;
            int servicesock = accept(_listensock, (struct sockaddr*)&src, &len);
            if (servicesock < 0) {
                logMessage(FATAL, "accept error, %d:%s", errno, strerror(errno));
                exit(5);
            }
            uint16_t cli_port = ntohs(src.sin_port);
            std::string cli_ip = inet_ntoa(src.sin_addr);
            logMessage(NORMAL, "link success, servicesock:%d|%s:%d|\n", servicesock, cli_ip.c_str(), cli_port);
            Thread t(servicesock, cli_ip, cli_port, threadRoutine);
            t.run();
            t.join();
        }
    }

private:
    static void* threadRoutine(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData*>(args);
        dictOnline(td->_sock, td->_ip, td->_port);
        return nullptr;
    }

    int _listensock;
    std::string _ip;
    uint16_t _port;
    const static int gbacklog = 20;
};
